package com.qf.controller;

import com.qf.bean.User;
import com.qf.service.UserService;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
//import lombok.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;



@Controller
@RequestMapping("/user")
public class UserController {

    private  final String USER ="user";

    private final String CODE ="USERCODE";

    private final String REGISTER_PAGE = "user/register";

    private final  String LOGIN_PAGE = "user/login";

    @Autowired
    private UserService userService;
    //import org.springframework.beans.factory.annotation.Value;
    @Value("${apikey}")
    private String apikey;

    @RequestMapping("/login")
    public String login(String username,String password,HttpSession session,Model model){
        // 1判断参数是否合法。
        if(StringUtils.isEmpty(username)|| StringUtils.isEmpty(password)){
            //参数不合法
            return LOGIN_PAGE;
        }
        //2 参数合法 = 执行登录操作
        User user = userService.login(username,password);
        if (user != null){
            session.setAttribute(USER,user);
            return "redirect:/item/list";
        }else{
            //用户名或密码错误
            //给用户一点提示
            model.addAttribute("loginInfo","用户名或密码错误！");
            return LOGIN_PAGE;
        }
    }

    //发送手机短信  http://localhost/user/sendsms
    @RequestMapping("/sendsms")
    @ResponseBody
    public String sendSms(@RequestParam String phone,HttpSession session){
     String code = (int)((Math.random()*9+1)*100000)+"";
        System.out.println(code);
        //初始化clnt,使用单例方式

        //放session
        session.setAttribute(CODE,code);
        YunpianClient clnt = new YunpianClient(apikey).init();

        //发送短信API
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, phone);
        param.put(YunpianClient.TEXT, "【云片网】您的验证码是" + code);
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
        //释放clnt
        clnt.close();
        return "ok";
    }

    @RequestMapping("/checkusername")
    @ResponseBody //返回的数据不通过视图解析器，直接响应给浏览器
    public Map<String,Object> checkUsername(@RequestBody User user){
        //获取用户名
        String username = user.getUsername();
        //调用service判断是否可用
        Integer count = userService.checkUsername(username);
        //3响应数据
        Map<String,Object> result = new HashMap<>();
        result.put("data",count);
        return  result;
    }
    //跳转到注册页面 method = {RequestMethod.POST,RequestMethod.GET}
    @RequestMapping(value = "/register")
    public String register(@Valid User user, BindingResult bindingResult,
                           String registerCode,HttpSession session) {
        // 1. 判断参数.
        if(StringUtils.isEmpty(registerCode) || bindingResult.hasErrors()){
            // 参数不合法.
            return REGISTER_PAGE;
        }

        // 2. 判断验证码是否正确
        String userCode = (String) session.getAttribute(CODE);
        if(registerCode.equals(userCode)){
            // 验证码正确   开始注册功能.
            Integer count = userService.register(user);
            if(count == 1){
                // 注册成功.
                return "redirect:/user/login";
            }
        }
        // 转发到注册页面
        return REGISTER_PAGE;
    }


}
